package eshttp

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"

	"gitee.com/les49/esgo/eshttp/internal/header"
)

type HttpHeader struct {
	Key   string
	Value string
}

func doRquest(url, method string, headers []*HttpHeader, body any) ([]byte, error) {
	requestBody := new(bytes.Buffer)
	json.NewEncoder(requestBody).Encode(body)
	request, err := http.NewRequest(method, url, requestBody)
	if err != nil {
		return nil, err
	}

	for _, v := range headers {
		request.Header.Set(v.Key, v.Value)
	}

	client := &http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return respBody, nil
}

func PostJsonRequest(url string, body any) ([]byte, error) {
	headers := make([]*HttpHeader, 0, 1)
	headers = append(headers, &HttpHeader{
		Key:   header.ContentType,
		Value: header.ApplicationJson,
	})

	return doRquest(url, "POST", headers, body)
}

func PostJsonRequestWithHeaders(url string, headers []*HttpHeader, body any) ([]byte, error) {
	return doRquest(url, "POST", headers, body)
}

func GetWithBasicAuth(url, username, password string) ([]byte, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	req.SetBasicAuth(username, password)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return respBody, nil
}
